import React from 'react';
import {connect} from 'react-redux';
import menuRoute from 'routes/menuRoute';
import {messages} from "share/common";
import {Button, Table, Icon, Checkbox, message, Spin, Tooltip} from 'antd';
import ListSelector from 'components/list-selector';
import 'styles/setting/city-group/city-group-allot-company.scss';
import CityGroupService from 'containers/setting/city-group/city-group.service';
import ResizeTable from "components/resize-table";

class CityGroupAllotCompany extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      loading: false,
      listLoading: false,//左侧地点组列表是否loading
      columns: [
        { title: messages('setting.key173'/*公司代码*/), dataIndex: 'companyCode',
          render: (value) => {return (<Tooltip placement='left' title={value}>{value}</Tooltip>)}},
        { title: messages('setting.key174'/*公司名称*/), dataIndex: 'name',
          render: (value) => {return (<Tooltip placement='right' title={value}>{value}</Tooltip>)}},
      ],
      checkedList :[],//批量选择的地点组
      checkAll: false,//是否全选
      data: [],
      options: [],
      page: 0,
      size: 10,
      pagination: {
        total: 0,
        showQuickJumper: true,
      },
      deleted: false,
      visible: false,//分配公司的模态框是否弹出
      disabled: true,//批量分配公司按钮是否禁用
      backCityGroupInfo: menuRoute.getRouteItem('city-group', 'key'),
      clearText: messages("common.reset")/*重置*/,//重置按钮
      checkedPlace: {},//当前被选中的某一个地点组
    }
  };

  //获取列表和地点组数据
  componentWillMount(){
    this.getLevelCityList();
  };

  //获取左侧城市列表
  getLevelCityList = () => {
    const { deleted, options} = this.state;
    let params = [];
    this.setState({ listLoading: true });
    CityGroupService.getAllPlaceList(deleted).then(res => {
      res.data.map((item, index) => {
        params.push({
          label: item.levelName, id: item.id, value: item.levelOID, checked: index <= 0, checkboxChecked: false})
      });
      Object.assign(options, params);
      this.setState({
        listLoading: false,
        options,
        checkedPlace: options[0],
      }, () => {
        this.getPlaceCompany(this.state.options[0].value)
      });
    }).catch(() => {
      this.setState({ listLoading: false });
      message.error(messages('common.error1'))
    });
  };

  //点击全选时
  onCheckAllChange = () => {
    const {options, checkAll, checkedList} = this.state;
    options.map(item => {
      item.checkboxChecked = !checkAll;
      item.checkboxChecked ? checkedList.addIfNotExist(item) : checkedList.delete(item)
    });
    this.setState({
      checkedList: checkedList,
      checkAll: !checkAll,
      disabled: !checkedList.length,
    });
  };

//选中每一个地点组的checkbox时
  onCheckBoxChange = (option,index,e) => {
    e.stopPropagation();
    const {options, checkedList} = this.state;
    option.checkboxChecked = !option.checkboxChecked;
    option.checkboxChecked ? checkedList.addIfNotExist(option) : checkedList.delete(option);
    this.setState({
      checkedList,
      checkAll:  checkedList.length === options.length,
      disabled: !checkedList.length,
      page: 0,
      size: 10,
    });
  };

//单选时右侧列表数据
  onCheckChange = (option,index) => {
    const { options} = this.state;
    options.map((item,num) =>{
      item.checked = num === index;
    });
    this.setState({
      loading: true,
      options,
      checkedPlace: option,
    },() => {
      this.getPlaceCompany(this.state.checkedPlace.value)
    });
  };

  //获取右侧列表数据
  getPlaceCompany = (levelOID) => {
    const { page, size} = this.state;
    this.setState({
      loading: true,
    });
    CityGroupService.getPlaceListCompany(levelOID, page, size).then(res => {
      if(res.status === 200){
        this.setState({
          data: res.data,
          loading: false,
          pagination: {
            total: Number(res.headers['x-total-count'] || 0),
            current: this.state.page + 1,
            onChange: this.onPageChange
          }
        });
      }
      else{
        message.error(messages('setting.key175'/*数据加载失败，请重试*/))
      }
    })
  };


  //点击分页
  onPageChange = (page) => {
    if(page - 1 !== this.state.page){
      this.setState({
        page: page - 1
      }, () => {
        this.getPlaceCompany(this.state.checkedPlace.value);
      });
    }
  };

  //点击批量分配公司
  handleClick = () =>{
    this.setState({
      visible: true
    });
  };

  //点击模态框的OK
  handleModalOK = (result) => {
    const {checkedList, checkedPlace} = this.state;
    let companyOIDs = '';
    let levelOIDs = '';
    if(!result.result.length){
      message.error(messages('setting.key176'/*请先选择公司*/));
      this.setState({
        visible: true,
      });
    }else{
      this.setState({
        loading: true,
      });
      result.result.map(item => {
        companyOIDs += `companyOIDs=${item.companyOID}&`
      });
      if(checkedList.length){
        checkedList.map(item => {
          levelOIDs += `levelOIDs=${item.value}&`;
        });
      }else{
        levelOIDs += `levelOIDs=${checkedPlace.value}&`;
      }
      CityGroupService.allotCompany(companyOIDs, levelOIDs).then(res => {
        this.setState({
          loading: false,
        });
        message.success(messages("common.operate.success")/*操作成功*/)
      }).catch(err => {
        this.setState({
          loading: false,
        });
        message.error(messages('setting.key175'/*数据加载失败，请重试*/))
      });
      checkedList.map(item => {
        item.checkboxChecked = false
      });
      this.setState({
        checkAll: false,
        checkedList: [],
        visible: false,
      });
      this.getLevelCityList();
    }
  };

//点击模态框的取消
  handleModalCancel = () => {
    this.setState({
      visible:false
    });
  };

  render(){
    const {loading, listLoading, data, columns, pagination, options, checkAll, checkedList,
      visible, disabled, clearText, extraParams, backCityGroupInfo} = this.state;
    return (
      <div>
        <div className="company-left">
          <div style={{marginBottom: 10}}>
            <div style={{marginTop: 10, color: '#898585'}}>
              {messages("common.total1", {total: options.length})/*共 {options.length }条数据*/}/
              {messages("common.total.selected", {total: checkedList.length})/*已选{checkedList.length }条*/}
              <div style={{marginLeft: 20, display: 'inline-block'}}>
                <Button type="primary" onClick={()=>{this.handleClick()}} disabled={disabled} loading={loading}>
                  {messages('setting.key177'/*批量分配公司*/)}
                </Button>
              </div>
            </div>
            <div>
              <Spin spinning={listLoading}>
                <div className='city-list-checkAll'>
                  <Checkbox onChange={this.onCheckAllChange} checked={checkAll}>
                    {messages('setting.key178'/*全选当页*/)}
                  </Checkbox>
                </div>
                {
                  options.map((option,index)=>{
                      return (
                        <div key={index}
                             className={option.checked ? 'city-checked' : 'city-not-checked'}
                             onClick={()=>this.onCheckChange(option,index)}>
                          <Checkbox value={option.label}
                                    onChange={(e)=>{this.onCheckBoxChange(option,index,e)}}
                                    checked={option.checkboxChecked}>
                            {option.label}
                          </Checkbox>
                        </div>
                      )
                    }
                  )}
              </Spin>
            </div>
          </div>
          <div style={{fontSize: 14,margin: '20px 0',}}>
            <a onClick={() => {this.context.router.push(backCityGroupInfo.url)}}>
              <Icon type="rollback" />
              {messages("common.back")/*返回*/}
            </a>
          </div>
        </div>
        <div className="company-right">
          <div style={{fontSize: 18, fontWeight: 'bold'}}>
            {messages('setting.key179'/*分配城市组*/)}
          </div>
          <div style={{marginTop: 16, marginBottom: 16}}>
            <Button type="primary" onClick={()=>{this.handleClick()}}>
              {messages('setting.key180'/*添加公司*/)}
            </Button>
          </div>
          <div>
            <ResizeTable
              rowKey={(record, index) => index}
              dataSource={data}
              columns={columns}
              pagination={pagination}
              size="middle"
              loading={loading}
              bordered
            />
          </div>
        </div>
        <ListSelector type='batch_allot_company'
                      visible={visible}
                      onOk={this.handleModalOK}
                      extraParams={{source: checkedList.length === 1 ? checkedList[0].id : ''}}
                      onCancel={()=> this.handleModalCancel()}
                      clearText={clearText}
                      confirmLoading={loading}
        />
      </div>
    )
  }

}

CityGroupAllotCompany.contextTypes = {
  router: React.PropTypes.object
};
function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
  }
}

export default connect(mapStateToProps)(CityGroupAllotCompany);
